package com.wisdom.system.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.wisdom.system.manage.core.APIRequest;
import com.wisdom.system.manage.domain.ResultBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@RestController
@RequestMapping(value = "/api")
public class RequestController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${wisdom.system.path.api}")
    private String apiPath;

    @PostMapping("login")
    public ResultBody login(HttpServletRequest request) throws IOException {
        ResultBody resultBody = new ResultBody();
        APIRequest apiRequest = new APIRequest();
        String tokenJSON = apiRequest.requestToken(apiPath + "/oauth/token", request);
        logger.info(tokenJSON);
        JSONObject jsonObject = JSONObject.parseObject(tokenJSON);
        if (jsonObject.containsKey("access_token")) {
            HttpSession session = request.getSession();
            session.setAttribute("tokenJSON", jsonObject);
            resultBody.setCode("0");
            resultBody.setMsg("登录成功!");
            resultBody.setResult(jsonObject);
        } else {
            resultBody.setCode("401");
            resultBody.setMsg("用户账号或密码不正确!");
            resultBody.setResult(jsonObject);
        }
        return resultBody;
    }

    @RequestMapping("/transmit")
    private String transmit(HttpServletRequest request) throws IOException {
        String method = request.getMethod().toUpperCase();
        String result = "";
        HttpSession session = request.getSession();
        JSONObject jsonObject = (JSONObject) session.getAttribute("tokenJSON");
        if (jsonObject != null && jsonObject.containsKey("access_token")) {
            String accessToken = jsonObject.getString("access_token");
            String url = "";
            APIRequest apiRequest = new APIRequest();
            switch (method) {
                case "GET":
                    result = apiRequest.get(accessToken, request);
                    break;
                case "POST":
                    result = apiRequest.post(accessToken, request);
                    break;
                case "PUT":

                    break;
                case "DELETE":
                    break;
            }
        }
        return result;
    }
}
